package com.cheetah.support.mongo;

import com.cheetah.config.Mongo;
import com.mongodb.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * @Author Administrator
 * @Date 2019/9/26
 * @Version V1.0
 * @Description: 根据配置获取不同实例库的mongoTemplate
 **/
@Slf4j
public class MongoTemplateProcessor {

    public static final String MONGO = "MONGO_";

    public static MongoTemplate getMongoTemplate(Mongo mongo){
        List<ServerAddress> list = new ArrayList<>();
        Arrays.stream(Optional.of(mongo.getNodes()).orElse("").split(",")).forEach(k -> {
            String[] nodes = Optional.of(k).orElseThrow(RuntimeException::new).trim().split(":");
            list.add(new ServerAddress(nodes[0],Integer.valueOf(nodes[1])));
        });

        MongoClientOptions mco = MongoClientOptions.builder()
                .connectionsPerHost(mongo.getConnectionsPerHost())
                .maxWaitTime(mongo.getMaxWaitTime())
                .threadsAllowedToBlockForConnectionMultiplier(mongo.getThreadsAllowedToBlockForConnectionMultiplier())
                .connectTimeout(mongo.getConnectTimeout())
                .retryWrites(mongo.isRetryWrites())
                .writeConcern(WriteConcern.JOURNALED)
                .readPreference(ReadPreference.secondaryPreferred())
                .build();

        MongoClient client = null;
        log.info("init mongo config:{}",mongo);
        if(mongo.getUsername() != null && mongo.getPassword() != null){
            MongoCredential mongoCredential = MongoCredential.createMongoCRCredential(mongo.getUsername(),mongo.getDatabase(),mongo.getPassword().toCharArray());
            client = new MongoClient(list,mongoCredential,mco);
        }else {
            client =  new MongoClient(list,mco);
        }
        return new MongoTemplate(client,mongo.getDatabase());
    }
}
